package com.epam.iunna.bookshop.model;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
import com.epam.iunna.bookshop.model.util.ConnectionsPool;
import com.epam.iunna.bookshop.model.util.DBUtils;

public class OrderDao {
    public Order getById(Long id) throws SQLException {
        Connection connection = null;
        ResultSet result = null;
        PreparedStatement statement = null;
        Order order = null;

        try {

            connection = ConnectionsPool.getInstance().getConnection();

            // Do we have a connection?
            if (!connection.isClosed()) {
                // We have a MySQL Connection.
                statement = connection
                        .prepareStatement("select * from BookStore.order where id=?");
                statement.setLong(1, id);
                statement.executeQuery();
                result = statement.getResultSet();
                if (result.next()) {
                    return getOrderPojo(result);
                }
            }
        } finally {
            closeConnection(connection, statement, result);
        }
        return order;
    }

    public Order getByDate(Date date) throws SQLException {
        Connection connection = null;
        ResultSet result = null;
        PreparedStatement statement = null;
        Order order = null;

        try {

            connection = ConnectionsPool.getInstance().getConnection();

            // Do we have a connection?
            if (!connection.isClosed()) {
                // We have a MySQL Connection.
                statement = connection
                        .prepareStatement("select * from order where date=?");
                statement.setDate(1, date);
                statement.executeQuery();
                result = statement.getResultSet();
                if (result.next()) {
                    return getOrderPojo(result);
                }
            }
        } finally {
            closeConnection(connection, statement, result);
        }
        return order;
    }

    public List<Order> getByUser(Long user) throws SQLException {
        Connection connection = null;
        ResultSet result = null;
        PreparedStatement statement = null;
        List<Order> orderList = new LinkedList<Order>();

        try {

            connection = ConnectionsPool.getInstance().getConnection();

            // Do we have a connection?
            if (!connection.isClosed()) {
                // We have a MySQL Connection.
                statement = connection
                        .prepareStatement("select * from BookStore.order where user=?");
                statement.setLong(1, user);
                statement.executeQuery();
                result = statement.getResultSet();
                
                do{
                    result.next();
                    orderList.add( getOrderPojo(result));
                }while(!result.isLast());
            }
        } finally {
            closeConnection(connection, statement, result);
        }
        return orderList;
    }

    public Order getByPaymentStatus(Boolean paymentStatus) throws SQLException {
        Connection connection = null;
        ResultSet result = null;
        PreparedStatement statement = null;
        Order order = null;

        try {

            connection = ConnectionsPool.getInstance().getConnection();

            // Do we have a connection?
            if (!connection.isClosed()) {
                // We have a MySQL Connection.
                statement = connection
                        .prepareStatement("select * from order where paymentStatus=?");
                statement.setBoolean(1, paymentStatus);
                statement.executeQuery();
                result = statement.getResultSet();
                if (result.next()) {
                    return getOrderPojo(result);
                }
            }
        } finally {
            closeConnection(connection, statement, result);
        }
        return order;
    }
    public Order setByPaymentStatus(Order orderPojo,Boolean paymentStatus) throws SQLException {
        Connection connection = null;
        ResultSet result = null;
        PreparedStatement statement = null;
        Order order = null;

        try {

            connection = ConnectionsPool.getInstance().getConnection();

            // Do we have a connection?
            if (!connection.isClosed()) {
                // We have a MySQL Connection.
                statement = connection
                        .prepareStatement("update order set paymentStatus=? where id=?");
                statement.setBoolean(1, paymentStatus);
                statement.setLong(2,orderPojo.getId());
                statement.executeQuery();
                result = statement.getResultSet();
                if (result.next()) {
                    return getOrderPojo(result);
                }
            }
        } finally {
            closeConnection(connection, statement, result);
        }
        return order;
    }
    public List<Order> getAll() throws SQLException {
        Connection connection = null;
        ResultSet result = null;
        Statement statement = null;

        List<Order> orderList = new LinkedList<Order>();

        try {

            connection = ConnectionsPool.getInstance().getConnection();

            // Do we have a connection?
            if (!connection.isClosed()) {
                // We have a MySQL Connection.
                statement = connection.createStatement();
                statement.executeQuery("select * from order");
                result = statement.getResultSet();
                while (result.next()) {
                    orderList.add(getOrderPojo(result));
                }
                return orderList;
            }
        } finally {
            closeConnection(connection, statement, result);
        }
        return null;
    }
    
    public void updatePaymentStatus(Order order) throws SQLException{
        Connection connection = null;
        PreparedStatement statement = null;

        try {

            connection = ConnectionsPool.getInstance().getConnection();

            // Do we have a connection?
            if (!connection.isClosed()) {
                // We have a MySQL Connection.
                statement = connection
                        .prepareStatement("update BookStore.order set paymentStatus=? where id=?");
                statement.setBoolean(1, order.getPaymentStatus());
                statement.setLong(2, order.getId());
                
                statement.executeUpdate();

            }else{
                throw new SQLException("Cannot obtain db connection.");
            }
        } finally {
            DBUtils.closeConnection(connection, statement, null);
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

    /**
     * @param connection
     *            connection to db
     * @param statement
     *            statement to db * @param result result set from db
     * @throws SQLException
     */
    private void closeConnection(Connection connection, Statement statement,
            ResultSet result) throws SQLException {
        try {
            if (result != null) {
                result.close();// close result set
            }
        } finally {
            try {
                if (statement != null) {
                    statement.close();// close statement
                }
            } finally {
                // If we don't have a error, close the connection!
                if (connection != null) {
                    connection.close();
                }
            }
        }
    }

    public Long addOrder(Order order) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;

        try {

            connection = ConnectionsPool.getInstance().getConnection();

            // Do we have a connection?
            if (!connection.isClosed()) {
                // We have a MySQL Connection.
                statement = connection
                        .prepareStatement("insert into BookStore.order (date,user,paymentStatus, notes, address) values (?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
              
                
                statement.setDate( 1, order.getDaten() );
                statement.setLong( 2, order.getUser() );
                statement.setBoolean( 3, order.getPaymentStatus() );
                statement.setString( 4, order.getNotes() );
                statement.setString( 5, order.getAddress() );
                
                statement.executeUpdate();
                
                ResultSet generatedKeys = statement.getGeneratedKeys();
                if (generatedKeys.next()) {
                    return generatedKeys.getLong(1);
                } else {
                    throw new SQLException("Creating Order failed, no generated key obtained.");
                }

            }else{
                throw new SQLException("Cannot obtain db connection.");
            }
        } finally {
            DBUtils.closeConnection(connection, statement, null);
        }
    }
    
    /**
     * @param userRecord
     *            user record from db
     * @return User POJO
     * @throws SQLException
     */
    private Order getOrderPojo(ResultSet orderRecord) throws SQLException {
        Order order = new Order();
        order = new Order();
        order.setId(orderRecord.getLong("id"));
        order.setDate(orderRecord.getDate("date"));
        order.setPaymentStatus(orderRecord.getBoolean("paymentStatus"));
        order.setNotes(orderRecord.getString("notes"));
        order.setAddress(orderRecord.getString("address"));
        order.setUser(orderRecord.getLong("user"));
        return order;
    }
    
   
}
